package hangler

import (
	"github.com/gin-gonic/gin"
	"login-kit/models"
	"login-kit/pkg"
	"strconv"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	data := models.User{
		Name:     name,
		Password: password,
	}
	err := models.DB.Where("name = ?", name).First(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "未找到该用户",
		})
		return
	}
	if pkg.Md5(password) != data.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登陆成功",
		})
		return
	}
}

func Str(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	content := c.PostForm("content")
	data := models.User{
		Name:     name,
		Password: password,
		Content:  content,
	}
	ext := models.DB.Begin()
	err := ext.Create(&data).Error
	if err != nil {
		ext.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		ext.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}
func Role(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	author := c.PostForm("author")
	data := models.Role{
		Name:    name,
		Content: content,
		Author:  author,
	}
	ext := models.DB.Begin()
	err := ext.Create(&data).Error
	if err != nil {
		ext.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		ext.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.User{}).Count(&count)
	var user []models.User
	err := models.DB.Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"user":  user,
		},
	})
	return
}
